package hyl.ext.base;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson2.JSON;
import hyl.core.MyFun;
import hyl.core.info.Content;
public class Response {
	public static final String ATTR_TOKEN = "TOKEN";

	public static final String getBasePath(HttpServletRequest request) {
		String path = request.getContextPath();
		String baseurl = "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
		return request.getScheme() + baseurl;
	}
	public static void forwardOrJson(HttpServletRequest request, HttpServletResponse response, String url, Content ct)
			throws ServletException, IOException {
		// 判断是否为ajax请求，默认不是
		boolean isAjaxRequest = false;
		if (!MyFun.isEmpty(request.getHeader("x-requested-with"))
				&& request.getHeader("x-requested-with").equals("XMLHttpRequest")) {
			isAjaxRequest = true;
		}
		if (isAjaxRequest) {
			if (ct != null)
				write(response, ct);
		} else {
			if (ct != null)
				request.setAttribute("ct", ct);
			forward(request, response, url);
		}
	}
	public static void forward(HttpServletRequest req, HttpServletResponse res, String 跳转地址) {
		// "/WEB-INF/jsp/login.jsp"
		try {
			req.getRequestDispatcher(跳转地址).forward(req, res);
		} catch (IOException | ServletException e) {
			e.printStackTrace();
		}
	}
	public static void directOrJson(HttpServletRequest request, HttpServletResponse response, String url, Content ct)
			throws ServletException, IOException {
		// 判断是否为ajax请求，默认不是
		boolean isAjaxRequest = false;
		if (!MyFun.isEmpty(request.getHeader("x-requested-with"))
				&& request.getHeader("x-requested-with").equals("XMLHttpRequest")) {
			isAjaxRequest = true;
		}
		if (isAjaxRequest) {
			if (ct != null)
				write(response, ct);
		} else {
			if (ct != null)
				request.setAttribute("ct", ct);
			direct(response, url);
		}
	}
	public static void direct(HttpServletResponse res, String 跳转地址) {
		try {
			res.sendRedirect(跳转地址);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void write(HttpServletResponse res, Content ct) {
		write(res, JSON.toJSONString(ct.get()));
	}
	public static void write(HttpServletResponse res, String str) {
		PrintWriter out;
		try {
			res.setContentType("application/json;charset=UTF-8");
			out = res.getWriter();
			out.write(str);
			out.flush();
			out.close();
			// res.flushBuffer();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void showCookies(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();// 根据请求数据，找到cookie数组
		for (Cookie cookie : cookies) {
			System.out.println("cookieName:" + cookie.getName() + ",cookieValue:" + cookie.getValue());
		}
	}
	public static void addCookie(HttpServletResponse rep, String key, String value, int expired) {
		addCookie(rep, null, key, value, expired);
	}
	// 创建cookie，并将新cookie添加到“响应对象”response中。
	public static void addCookie(HttpServletResponse response, String path, String cookieName, String value,
			int maxage) {
		Cookie cookie = new Cookie(cookieName, value);// 创建新cookie
		if (path == null)
			path = "/";
		if (maxage > 0)
			cookie.setMaxAge(maxage);// 设置存在时间为5分钟
		cookie.setPath(path);// 设置作用域
		response.addCookie(cookie);// 将cookie添加到response的cookie数组中返回给客户端
	}
	// 修改cookie，可以根据某个cookie的name修改它（不只是name要与被修改cookie一致，path、domain必须也要与被修改cookie一致）
	public static void editCookie(HttpServletRequest request, HttpServletResponse response, String path,
			String cookieName, String value, int maxage) {
		Cookie[] cookies = request.getCookies();
		if (path == null)
			path = "/";
		for (Cookie cookie : cookies) {
			// 迭代时如果发现与指定cookieName相同的cookie，就修改相关数据
			if (cookie.getName().equals(cookieName)) {
				cookie.setValue(value);// 修改value
				cookie.setPath(path);
				if (maxage > 0)
					cookie.setMaxAge(maxage);// 修改存活时间
				response.addCookie(cookie);// 将修改过的cookie存入response，替换掉旧的同名cookie
				break;
			}
		}
	}
	// 删除cookie
	public static void delCookie(HttpServletRequest request, HttpServletResponse response, String path,
			String cookieName) {
		Cookie[] cookies = request.getCookies();
		if (path == null)
			path = "/";
		for (Cookie cookie : cookies) {
			// 如果找到同名cookie，就将value设置为null，将存活时间设置为0，再替换掉原cookie，这样就相当于删除了。
			if (cookie.getName().equals(cookieName)) {
				cookie.setValue(null);
				cookie.setMaxAge(0);
				cookie.setPath("/");
				response.addCookie(cookie);
				break;
			}
		}
	}
	public static String getCookie(HttpServletRequest request, String cookieName) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null || cookieName == null || cookieName.equals(""))
			return null;
		for (Cookie c : cookies) {
			if (c.getName().equals(cookieName))
				return c.getValue();
		}
		return null;
	}
	public static String getCookie(HttpServletRequest request, HttpServletResponse response, String path) {
		String value = null;
		if (MyFun.isEmpty(path))
			return null;
		Cookie[] cooks = request.getCookies();
		if (cooks != null) {
			for (Cookie c : cooks) {
				if (c.getName().equals(path)) {
					value = c.getValue();
				}
				// System.out.println("##"+c.getName()+"="+c.getMaxAge());
				c.setMaxAge(0); // 立即过期
				response.addCookie(c);
			}
		}
		return value;
	}
	public static void clearCookie(HttpServletRequest req, HttpServletResponse res) {
		Cookie[] cooks = req.getCookies();
		if (cooks != null) {
			for (Cookie c : cooks) {
				c.setMaxAge(0); // 立即过期
				res.addCookie(c);
			}
		}
	}
	/**
	 * 获取访问者IP
	 * 
	 * 在一般情况下使用Request.getRemoteAddr()即可，
	 * 
	 * 但是经过nginx等反向代理软件后，这个方法会失效。
	 * 
	 * 本方法先从Header中获取X-Real-IP，
	 * 
	 * 如果不存在再从X-Forwarded-For获得第一个IP(用,分割)， 
	 * 
	 * 如果还不存在则调用Request.getRemoteAddr()。
	 * 
	 * @param request
	 * @return
	 */
	public static String getIPAddress(HttpServletRequest request) {
		// X-Forwarded-For：Squid 服务代理
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			// Proxy-Client-IP：apache 服务代理
			ip = request.getHeader("Proxy-Client-IP");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				// WL-Proxy-Client-IP：weblogic 服务代理
				ip = request.getHeader("WL-Proxy-Client-IP");
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					// HTTP_CLIENT_IP：有些代理服务器
					ip = request.getHeader("HTTP_CLIENT_IP");
					if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
						// X-Real-IP：nginx服务代理
						ip = request.getHeader("X-Real-IP");
						if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
							// X-Real-IP：nginx服务代理
							ip = request.getHeader("HTTP_X_FORWARDED_FOR");
							if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
								ip = request.getHeader("PROXY_FORWARDED_FOR");
								// 还是不能获取到，最后再通过request.getRemoteAddr();获取
								if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
									ip = request.getRemoteAddr();
								}
							}
						}
					}
				}
			}
		}
		if (ip.equals("0:0:0:0:0:0:0:1")) {
			return "127.0.0.1";
		}
		// 有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
		if (ip.indexOf(",") > 0) {
			ip = ip.substring(0, ip.indexOf(","));
		}
		return ip;
	}
	// 取本机的网卡IP
	public static String getHostAddress() {
		InetAddress inet = null;
		try {
			inet = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return inet.getHostAddress();
	}
	public static String getClientIpPort(HttpServletRequest request) {
		return getIPAddress(request) + '_' + request.getRemotePort();
	}
	//????待测试
	public static boolean is来自本地(HttpServletRequest request) {
		String path=request.getRemoteAddr();
		MyFun.print(path);
		if (path.startsWith("127.")||path.startsWith("192.")||path.startsWith("172.")||path.startsWith("10.")||path.startsWith("localhost")) return true;
		return false;		
	}
	
}
